package com.abe.mvp.view.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;

import com.abe.config.SerialPortConstants;
import com.abe.config.StrengthtrainerSericalPortUtils;
import com.abe.mvp.contact.SerialPortContact;
import com.abe.mvp.model.bean.DeviceBean;
import com.abe.mvp.model.bean.SerialPortDataBean;
import com.abe.mvp.model.bean.SerialPortParseBean;
import com.abe.mvp.model.bean.exercise.ExerciseSTNodeBean;
import com.abe.mvp.presenter.SerialPortPresenterImp;
import com.abe.utils.CRCChecker;
import com.abe.utils.JsonHelper;
import com.abe.utils.NormalUtils;
import com.abe.utils.ThreadPoolUtils;

public class MainBallOldOldActivity extends MainBallViewOldOldActivity {
	/** 串口相关 */
	private SerialPortContact.Presenter serialPortPresenter;
	/** socket相关 */
	// private SocketContact.Presenter socketPresenter;

	//private SettingBean settingBean;

	private int sendCount = 0;
	private int readOriginalCount = 0;
	private int readCount = 0;
	private List<SerialPortDataBean> serialPortDataBeans = new ArrayList<>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		serialPortPresenter = new SerialPortPresenterImp(this);
		// socketPresenter = new SocketPresenterImp(this);
		serialPortPresenter
				.openSerialPort(SerialPortConstants.SerialPort_ttys3);
		//settingBean = SettingParam.getSettingBean();
		// socketPresenter.openSocket(settingBean.getSocketIp(),settingBean.getSocketPort());
		requestStart();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (serialPortPresenter != null) {
			serialPortPresenter.closeSerialPort();
			serialPortPresenter = null;
		}
		// if (socketPresenter != null) {
		// socketPresenter.closeSocket();
		// socketPresenter = null;
		// }
	}

	@Override
	public void sendSericalPortCommand(byte[] command) {
		serialPortPresenter.sendCommand(command);
		localCustomSendMessage(MAIN_REFRESH_SEND, JsonHelper.toJson(command));
	}

	@Override
	public void startSuccess() {
		exerciseStartTime = System.currentTimeMillis();
		/** 启动读数据线程 */
		ThreadPoolUtils.execute(new TransmissionThread());
		/** 启动小球刷新线程 */
		// ThreadPoolUtils.execute(new RefreshBallHeightThread());
		// logBuilder.append("启动成功").append("\n");
		isExercise = true;
		/** 启动曲线移动 */
		localCustomSendMessage(MAIN_REFRESH_SHOW, "");
		localCustomSendEmptyMessage(MAIN_REFRESH_SHOW_CURVE);
	}

	@Override
	public void stopSuccess() {
		// logBuilder.append("停止成功").append("\n");
		NormalUtils.saveCrashInfo2File(
				"通信日志",
				new StringBuilder("send=").append(sendCount).append("\n")
						.append("read=").append(readCount).append("\n")
						.append("readOriginal=").append(readOriginalCount)
						.toString());
		// StringBuilder builder = new StringBuilder();
		// for (int i = 0; i < serialPortDataBeans.size(); i++) {
		// builder.append(JsonHelper.toJson(serialPortDataBeans.get(i)))
		// .append("\n");
		// }
		// NormalUtils.saveCrashInfo2File("接收数据日志", builder.toString());
		// NormalUtils.saveCrashInfo2File("通信流程日志", logBuilder.toString());
		exerciseStopTime = System.currentTimeMillis();
		groupBean.setKeepTime((int) (exerciseStopTime - exerciseStartTime));
		/** 关闭曲线移动 */
		callStopMove();
		/** 跳转展示运动信息 */
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("exercise", groupBean);
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		back();
	}

	class TransmissionThread implements Runnable {

		@Override
		public void run() {
			isExercise = true;
			/** 读命令 */
			byte[] READ_DATA = CRCChecker
					.getSendBuf(StrengthtrainerSericalPortUtils.READ_DATA);
			while (isExercise) {
				// logBuilder.append("请求发送读命令").append("\n");
				try {
					/** 发送读命令 */
					if (serialPortPresenter != null && !isSetStartStopCommand) {
						serialPortPresenter.sendCommand(READ_DATA);
						localCustomSendMessage(MAIN_REFRESH_SEND,
								JsonHelper.toJson(READ_DATA));
						sendCount++;
						// logBuilder.append("已发送读命令").append("\n");
					} else {
						// logBuilder.append("未发送读命令").append("\n");
					}
					/** 等待时间 */
					Thread.sleep(readDataRate);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/********************************* 串口相关 **************************************/

	@Override
	public void onReceiveData(Boolean isSuccess, SerialPortDataBean data) {
		if (isSuccess) {
			// logBuilder.append("接到返回数据，并解析").append("\n");
			readOriginalCount++;
			serialPortDataBeans.add(data);
			SerialPortParseBean parseBean = StrengthtrainerSericalPortUtils
					.parse(data);
			if (parseBean.isVerifyStatus()) {
				// logBuilder.append("数据校验成功").append("\n");
				if (parseBean.getUseType() == 0) {
					// logBuilder.append("读命令返回数据").append("\n");
					readCount++;
					/** 读操作返回成功 */
					DeviceBean deviceBean = parseBean.getReadData();
					/** 判断是否设置完毕 */
					if (!isRecordEnd) {
						boolean recordEnd = deviceBean.isRecordEnd();
						if (recordEnd) {
							isRecordEnd = recordEnd;
							customMaxHeight = deviceBean.getMaxHeight();
							localCustomSendMessage(MAIN_REFRESH_RECEIVE, "最大："
									+ customMaxHeight);
							/** 初始化图形相关 */
							int preparaTime = deviceBean.getPreparaTime();
							int pushTime = deviceBean.getPushTime();
							int keepMaxTime = deviceBean.getKeepMaxTime();
							int returnTime = deviceBean.getReturnTime();
							macv.setPreparaTime(preparaTime);
							macv.setPushTime(pushTime);
							macv.setKeepMaxTime(keepMaxTime);
							macv.setReturnTime(returnTime);
							callStartMove();
						}
					} else {
						/** (串口控制) 启动或者停止 */
						boolean new_status = deviceBean.isControl();
						if (isExercise != new_status) {
							isExercise = new_status;
							if (isExercise) {
								// logBuilder.append("控制板启动成功").append("\n");
								startSuccess();
							} else {
								// logBuilder.append("控制板停止成功").append("\n");
								stopSuccess();
							}
						} else {
							/** 更新显示信息 */
							int count = deviceBean.getCount();
							currentCustomWeight = deviceBean.getWeight();
							currentCustomHeight = deviceBean.getHeight();
							if (oldCustomWeight != currentCustomWeight) {
								/** 重量重新设置节点 */
								ExerciseSTNodeBean nodeBean = new ExerciseSTNodeBean();
								nodeBean.setNodeWeight(currentCustomWeight);
								nodeBean.setNodeCount((count > 0) ? count - 1
										: 0);
								oldCustomWeight = currentCustomWeight;
								nodeBeans.add(nodeBean);
							}
							/** 更新重量 */
							localCustomSendMessage(MAIN_REFRESH_WEIGHT,
									currentCustomWeight);
							/** 更新次数 */
							localCustomSendMessage(MAIN_REFRESH_COUNT, count);
							/** 更新小球位置 */
							localCustomSendEmptyMessage(MAIN_REFRESH_BALL_POS);
							/** 刷新锻炼数据 */
							refreshExerciseGroupData(count);
							localCustomSendMessage(MAIN_REFRESH_RECEIVE, "最大："
									+ customMaxHeight + "---实时："
									+ currentCustomHeight);
						}
					}
				} else {
					// logBuilder.append("写命令返回数据").append("\n");
					/** 写操作成功 */
					if (!isExercise && isSetStartStopCommand) {
						// logBuilder.append("写启动成功").append("\n");
						/** 启动成功 */
						isExercise = true;
						isSetStartStopCommand = false;
						startSuccess();
					} else if (isExercise && isSetStartStopCommand) {
						// logBuilder.append("写停止成功").append("\n");
						/** 停止成功 */
						isExercise = false;
						isSetStartStopCommand = false;
						stopSuccess();
					}
				}
			} else {
				// logBuilder.append("数据校验失败").append("\n");
				/** 数据校验失败 */
			}
		} else {
			// logBuilder.append("未接到返回数据").append("\n");
		}
	}

	/********************************** socket相关 *************************************/

	@Override
	public void onSocketError(String errorMsg) {
		/** socket异常 */
		// if (socketPresenter != null) {
		// /** 开启socket轮询来一直请求连接socket */
		// socketPresenter.openSocket(settingBean.getSocketIp(),
		// settingBean.getSocketPort());
		// }
	}

}
